import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class AndroidProxy extends JFrame implements Runnable{

	private static String GAME_SERVER_HOST = "192.168.0.6";
	private static int GAME_SERVER_PORT = 7001;
	private static int ANDROID_PORT = 7002;

	Socket incoming;
	Socket outgoing;
	DataInputStream incomingData;
	DataOutputStream outgoingData;

	public AndroidProxy() {
		JTextArea jtaLog = new JTextArea();
		JScrollPane scrollPane = new JScrollPane(jtaLog);

		add(scrollPane, BorderLayout.CENTER);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 300);
		setTitle("TicTacToeServer");
		setVisible(true);

		// try to connect to Game Server
		try {
			incoming = new Socket(GAME_SERVER_HOST, GAME_SERVER_PORT);
		} catch (Exception e) {
			System.out.println("failed to connect to game server");
			System.exit(0);
		}

		jtaLog.append("Connected to Game Server");

		// wait for android to connect
		try {
			ServerSocket ss = new ServerSocket(ANDROID_PORT);
			outgoing = ss.accept();
		} catch (Exception e) {
			System.out.println("failed to connect to android");
			System.exit(0);
		}

		jtaLog.append("Connected to Android");

		try {
			incomingData = new DataInputStream(incoming.getInputStream());
			outgoingData = new DataOutputStream(outgoing.getOutputStream());
		} catch (Exception e) {
			System.out.println("Couldn't create data streams");
			System.exit(0);
		}


		new Thread(this).start();
	}

	public static void main(String[] args) {
		AndroidProxy a = new AndroidProxy();
	}

	public void run() {
		while (true) {
			try {
				outgoingData.write(incomingData.read());
			}
			catch (Exception e) {
				System.out.println("error writing/reading data");
				System.exit(0);
			}
		}
	}

}
